import { request } from '../../assets/js/request.js';
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
Page({
  getStuSignInfo:function(e){
    wx.showLoading({
      title: '加载数据',
      mask: true,
    })
    let reqData1 = {
      stuId: this.data.stuId,
      classId: this.data.classId
    }
    request('/getStuSignInfo.php', reqData1)
      .then((res)=>{
        this.setData({
          signInfo: res.data.signInfo
        })
      })
      .catch((err)=>{
        Notify({ type: 'danger', message: '服务器繁忙，请稍后再试' });
      })
  },

  delInfo:function(e){
    wx.showModal({
      title: '提示',
      content: '你确定要删除该条记录吗？',
      success:(res) => {
        if(res.confirm){
          wx.showLoading({
            title: '正在删除',
            mask: true,
          })
          request('/delSignInfo.php', { signDelId: e.currentTarget.id})
            .then((res)=>{
              this.getStuSignInfo();
            })
            .catch((err)=>{
              Notify({ type: 'danger', message: '服务器繁忙，请稍后再试' });
            })
        }
      }
    })
  },

  addSignRecord:function(){
    if(this.data.date == ''){
      Toast({
        type: 'fail',
        message: '请选择日期',
        mask: true,
        duration: 1000
      })
    }else{
      wx.showLoading({
        title: '添加中',
        mask: true
      })
      let reqData2 = {
        uId: this.data.stuId,
        classId: this.data.classId,
        create_at: this.data.date
      }
      request('/addSignRecord.php', reqData2)
        .then((res)=>{
          if (res.data == 'ok') {
            Toast({
              type: 'success',
              message: '添加成功',
              mask: true,
              duration: 1000
            })
          } else if(res.data == 'repeat'){
            Toast({
              type: 'fail',
              message: '签到已存在',
              mask: true,
              duration: 1000
            })
          }
          this.getStuSignInfo();
        })
        .catch((err)=>{
          Notify({ type: 'danger', message: '服务器繁忙，请稍后再试' });
        })
    }
  },

  data: {
    stuId:'',
    classId:'',
    signInfo:[],
    signDelId:'',
    date: '',
    minDate: new Date(2020, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    show: false
  },

  onShow: function () {
    this.setData({
      stuId: wx.getStorageSync('stuId-sign'),
      classId: wx.getStorageSync('classId')
    })
    this.getStuSignInfo();
  },

  onUnload: function () {
    wx.removeStorageSync('stuId-sign');
  },

  onPullDownRefresh: function () {
    this.getStuSignInfo();
    wx.stopPullDownRefresh();
  },

  _onShow() {
    this.setData({ show: true });
  },
  _onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  _onConfirm(event) {
    this.setData({
      show: false,
      date: this.formatDate(event.detail)
    });
  }
})